﻿using Amib.Threading;
using HandyControl.Tools;
using HandyControl.Tools.Command;
using HandyControl.Tools.Extension;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using ZFBActivation.Core;
using ZFBActivation.Log;
using ZFBActivation.ThreadPool;

namespace ZFBActivation.Model
{
    public  class MainWindowModel: IPropertyChanged
    {
        public string QueryPwd {
            get { return this.GetValue(cu => cu.QueryPwd, "AS220033"); }
            set { this.SetValue(cu => cu.QueryPwd, value); }
        }
        public string PayPwd {
            get { return this.GetValue(cu => cu.PayPwd, "220033"); }
            set { this.SetValue(cu => cu.PayPwd, value); }
        }
        public int RunMax {
            get { return this.GetValue(cu => cu.RunMax,1); }
            set { this.SetValue(cu => cu.RunMax, value); }
        }
        //http代理平台 https://www.xiaoxiongip.com/ 18675688882  Abc2200334
        public string ProxyUrl {
            get { return this.GetValue(cu => cu.ProxyUrl, "https://find.xiaoxiongip.com/find_s5?key=7efc02eeabc22bd8&count=20&type=json&only=1&net=1&pw=no"); }
            set { this.SetValue(cu => cu.ProxyUrl, value); }
        }
        
        public ObservableCollection<MailPhone> MailItems {
            get { return this.GetValue(cu => cu.MailItems, new ()); }
            set { this.SetValue(cu => cu.MailItems, value); }
        }
        public MailPhone SelectedMailPhone {
            get { return this.GetValue(cu => cu.SelectedMailPhone); }
            set { this.SetValue(cu => cu.SelectedMailPhone, value); }
        }
        public string BrowserPath {
                get { return this.GetValue(cu => cu.BrowserPath); }
                set { this.SetValue(cu => cu.BrowserPath, value); }
        }

        public void Init() {
            var items = DbContext.DB.Select<MailPhone>().ToList();
            MailItems.AddRange(items);

            QueryPwd = SettingHelper.SysSetting.QueryPwd;
            PayPwd = SettingHelper.SysSetting.PayPwd ;
            RunMax = SettingHelper.SysSetting.RunMax;
            ProxyUrl = SettingHelper.SysSetting.ProxyUrl;
            BrowserPath = SettingHelper.SysSetting.BrowserPath;

        }

        public ICommand OpenFileCmd => DelegateCommand.Create(() => {
            var dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            if (dialog.ShowDialog() == false) return;

            string[] files = File.ReadAllLines(dialog.FileName, System.Text.Encoding.UTF8);

            List<MailPhone> list = new List<MailPhone>();

            foreach (var item in files) {
                if (string.IsNullOrEmpty(item) || item.StartsWith("https")) {
                    continue;
                }
                string[] kv = item.Split(new string[] { "---", "----" },StringSplitOptions.RemoveEmptyEntries);
                if (kv.Length < 2) {
                    continue;
                }
                MailPhone mailPhone = new MailPhone();
                mailPhone.Email = kv[0];
                mailPhone.Password = kv[1];
                mailPhone.Phone = kv[2];
                mailPhone.Msg = "待启动";
                list.Add(mailPhone);
            }

            int index = 0;
            foreach (var item in files) {
                if (string.IsNullOrEmpty(item) || !item.StartsWith("https")) {
                    continue;
                }
                //string[] kv = item.Split(new string[] { "----" }, StringSplitOptions.RemoveEmptyEntries);
                //if (kv.Length < 3) {
                //    continue;
                //}
                list[index].Url = item;
                index++;
            }
            MailItems.AddRange(list.OrderBy(t=>t.Phone));


            DbContext.DB.InsertOrUpdate<MailPhone>().SetSource(list).ExecuteAffrows();
        });

        public ICommand ClearAllCmd => DelegateCommand.Create(() => {

            MailItems.Clear();
            DbContext.DB.Delete<MailPhone>().Where(t=>t.Email != null).ExecuteAffrows();
        });
        public ICommand ExportSuccessCmd => DelegateCommand.Create(() => {
            var groupby = MailItems.Where(t => t.IsSuccess);

            StringBuilder sb = new StringBuilder();
            foreach (var item in groupby) {
                sb.AppendLine($"{item.Email} {item.Password} {item.Phone} {item.QueryPwd} {item.PayPwd}");
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog.FilterIndex = 1;
            var result = saveFileDialog.ShowDialog();
            if (result ?? false) {
                File.WriteAllText(saveFileDialog.FileName, sb.ToString(), System.Text.Encoding.UTF8);
            }
        });

        public ICommand ExportErrorCmd => DelegateCommand.Create(() => {
            var groupby = MailItems.Where(t => !t.IsSuccess);

            StringBuilder sb = new StringBuilder();
            foreach (var item in groupby) {
                sb.AppendLine($"{item.Email} {item.Password} {item.Phone} {item.QueryPwd} {item.PayPwd}");
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog.FilterIndex = 1;
            var result = saveFileDialog.ShowDialog();
            if (result ?? false) {
                File.WriteAllText(saveFileDialog.FileName, sb.ToString(), System.Text.Encoding.UTF8);
            }
        });

        public bool IsStart { get; set; } = false;

        public ICommand StartCmd => DelegateCommand.Create(() => {
            if(IsStart) {
                return;
            }
            IsStart = true;
            SettingHelper.SysSetting.QueryPwd = QueryPwd;
            SettingHelper.SysSetting.PayPwd = PayPwd;
            SettingHelper.SysSetting.RunMax = RunMax;
            SettingHelper.SysSetting.ProxyUrl = ProxyUrl;
            SettingHelper.SysSetting.BrowserPath = BrowserPath;

            SettingHelper.Sava();



            _ = Task.Run(async () => {

                var groupBy = MailItems.GroupBy(t => t.Phone);

                foreach (var item in groupBy) {
                    if (!IsStart) {
                        return;
                    }
                    int max = item.Count();

                    TBServer.Instance.Init(max);
                    TBServer.Instance.ReMax();

                    List<WordZFB>  reults = new List<WordZFB>();
                    foreach (var itemEmail in item) {
                        if(itemEmail.IsSuccess || itemEmail.IsInvalid) {
                            continue;
                        }
                        WordZFB word = new WordZFB();
                        word.m_model = itemEmail;
                        word.m_model.CacheKey = Guid.NewGuid().ToString("N");
                        //var proxy = await ProxyHelper.Instance.GetProxy(SettingHelper.SysSetting.ProxyUrl);
                        bool result = await word.DoWork(null);
                        if (result) {
                            reults.Add(word);
                        }
                    }
                    while(true) {
                        try {
                            foreach (var itemMailPhone in reults) {
                                if (await itemMailPhone.CheckSuccess()) {
                                    itemMailPhone.UpdateDbModel();
                                }
                            }
                            if (reults.All(t => t.IsEnd)) {
                                reults.Clear();
                                break;
                            }
                            await Task.Delay(1000);
                        }
                        catch (Exception ex) {
                            LogHelper.Log(LogDefine.LogError, ex, "循环检查注册状态异常");
                        }
                    }

                }
            });
        });

        public ICommand StopCmd => DelegateCommand.Create(() => {
            IsStart = false;


        });


        public ICommand SelectBrowserPathCmd => DelegateCommand.Create(() => {
            var dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            if (dialog.ShowDialog() == false) return;

            BrowserPath = dialog.FileName;
        });
        public ICommand DelHistoryRecord => DelegateCommand.Create(() => {
            if(SelectedMailPhone == null) {
                return;
            }
            DbContext.DB.Delete<MailPhone>().Where(t => t.Email == SelectedMailPhone.Email).ExecuteAffrows();
            MailItems.Remove(SelectedMailPhone);

        });
        public ICommand ExportAll => DelegateCommand.Create(() => {


            StringBuilder sb = new StringBuilder();
            foreach (var item in MailItems) {
                sb.AppendLine($"{item.Email} {item.Password} {item.Phone} {item.QueryPwd} {item.PayPwd} {item.Msg}");
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog.FilterIndex = 1;
            var result = saveFileDialog.ShowDialog();
            if (result ?? false) {
                File.WriteAllText(saveFileDialog.FileName, sb.ToString(), System.Text.Encoding.UTF8);
            }
        });
        
    }
}
